#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "cJSON.h"

#define APIKEY "apikey"
#define USERID "liuyu"

CURL* curl;

int turing_init()
{
	curl_global_init(CURL_GLOBAL_ALL);
	curl = curl_easy_init();
	curl_easy_setopt(curl, CURLOPT_URL,
			"http://openapi.tuling123.com/openapi/api/v2");
	return 0;
}

void turing_cleanup()
{
	curl_easy_cleanup(curl);
	curl_global_cleanup();
}

void turing_chat(char* input)
{
	cJSON* request = cJSON_CreateObject();
	cJSON_AddNumberToObject(request, "reqType", 0);

	cJSON* inputText = cJSON_CreateObject();
	cJSON* perception = cJSON_CreateObject();
	cJSON_AddStringToObject(inputText, "text", input);
	cJSON_AddItemToObject(perception, "inputText", inputText);
	cJSON_AddItemToObject(request, "perception", perception);

	cJSON* userInfo = cJSON_CreateObject();
	cJSON_AddStringToObject(userInfo, "apiKey", APIKEY);
	cJSON_AddStringToObject(userInfo, "userId", USERID);
	cJSON_AddItemToObject(request, "userInfo", userInfo);

	//puts(cJSON_Print(request));

	char* response;
	size_t resplen;

	FILE* fp = open_memstream(&response, &resplen);
	if (!fp)
		perror("open_memstream");
	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, cJSON_Print(request));	
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);	
	CURLcode res = curl_easy_perform(curl);
	if (res != CURLE_OK)
		puts(curl_easy_strerror(res));
	fclose(fp);

	cJSON_Delete(request);

	cJSON* resp = cJSON_Parse(response);
	//puts(cJSON_Print(resp));

	cJSON* intent = cJSON_GetObjectItemCaseSensitive(resp, "intent");
	cJSON* code = cJSON_GetObjectItemCaseSensitive(intent, "code");

	if (code->valueint < 10000)
	{
		puts(cJSON_Print(resp));
		return;
	}

	cJSON* results = cJSON_GetObjectItemCaseSensitive(resp, "results");
	cJSON* result;
	cJSON_ArrayForEach(result, results)
	{
		cJSON* resultType = cJSON_GetObjectItemCaseSensitive(result, "resultType");
		if (!strcmp(resultType->valuestring, "text"))
		{
			cJSON* values = cJSON_GetObjectItemCaseSensitive(result, "values");
			cJSON* text = cJSON_GetObjectItemCaseSensitive(values, "text");
			printf("> %s\n", text->valuestring);
		}
	}

	free(response);
	cJSON_Delete(resp);
}

int main()
{
	char inputbuf[512];

	turing_init();
	while(fgets(inputbuf, sizeof inputbuf, stdin))
	{
		turing_chat(inputbuf);
	}
	turing_cleanup();

	return 0;
}

